import sys
from PIL import Image  
import os  
import math  
import xml.etree.ElementTree as ET
import json

# 读取本地的JSON文件
def read_json_file(file_path):
    try:
        with open(file_path, "r", encoding="utf-8") as file:
            data = json.load(file)
            return data
    except FileNotFoundError:
        print("文件不存在！")
        return None
    except json.JSONDecodeError:
        print("JSON解码错误！")
        return None

# 将数据保存为JSON文件
def save_json_file(file_path, data, indent=4, separators=(", ", ": ")):
    with open(file_path, "w", encoding="utf-8") as file:
        json.dump(data, file, indent=indent, ensure_ascii=False, separators=separators)

def packMapData(file_path):
    mapData = {}
    # {"width":1920,"height":1440,"realHeight":23,"realWidth":30,"chunkw":512,"chunkh":512,"scale":0,"scalechunk":0,"datas":[],"path":[]}

    #解析XML文件
    tree = ET.parse(file_path)

    # 获取根元素
    root = tree.getroot()

    mapImage = root.find("imagelayer").find("image")
    mapData["width"] = int(mapImage.attrib["width"])
    mapData["height"] = int(mapImage.attrib["height"])
    mapData["src"] = mapImage.attrib["source"]
    gridDatas = root.findall("layer")
    tmp = []
    for child in gridDatas:
        mapData["gridW"] = int(child.attrib["width"])
        mapData["gridH"] =  int(child.attrib["height"])
        if len(tmp):
            nextData = list(map(int, child.find("data").text.replace("\n","").split(",")))  
            for i in range( len(tmp)) :
                tmp[i] = tmp[i] | nextData[i]
        else:
            tmp =list(map(int, child.find("data").text.replace("\n","").split(",")))  
        
    gridData = []
    gridW = mapData["gridW"]
    gridH = mapData["gridH"]
    for y in range(gridH-1,-1,-1):
        for x in range(gridW):
           gridData.append(tmp[y*gridW+x])
    mapData["datas"] = gridData
    return mapData
  

def split_image(image_path, output_dir, size=(256, 256)):  
    # 打开图片  
    img = Image.open(image_path)  
    width, height = img.size  
  
    # 计算行列数量  
    rows = math.ceil(height / size[1])  
    cols = math.ceil(width / size[0])  

    curY = height 
    for i in range(rows):  
        curX = 0
        for j in range(cols):  
            # 计算当前图片的位置和大小  
            box = (curX, max(curY - size[1],0) ,min([curX + size[0],width]) , curY )
            curX = curX + size[0]
            # 保存图片  
            try:  
                cropped_img = img.crop(box)  
                cropped_img.save(os.path.join(output_dir, f'{i}_{j}{os.path.splitext(image_path)[1]}'))  
            except IndexError:  
                # 当图片尺寸不是完美符合分割大小时，可能会产生IndexError，可以通过捕获异常来忽略这个问题  
                pass  
        curY = curY - size[1]
    img.close()

def create_small(image_path, output_dir, scale):
     # 打开图片  
    img = Image.open(image_path)  
    width, height = img.size  
    resized_image = img.resize((int(width * scale) ,int(height * scale)))  
    resized_image.save(os.path.join(output_dir,f"small{os.path.splitext(image_path)[1]}"))
    img.close()
  
if __name__ == "__main__":  
    conf = read_json_file("./conf.json")
    inDir = conf["tilemap_dir"]
    if not os.path.exists(inDir):
        input(f'conf.json tilemap_dir :{inDir}路径不存在')
    else:
        dirs = os.listdir(inDir)
        cwdDir = os.getcwd()
        os.chdir(inDir)
        for v in dirs:
            mapName = v.split(".")[0]
            if mapName in conf["convert_file"]:
                print(f"开始打包{mapName}")
                print(f"---->数据解析")
                mapData = packMapData(os.path.join(inDir,v))
                mapData["imgSize"] = conf["image_size"]
                mapDir = os.path.join( cwdDir,conf["out_dir"],mapName)
                imgDir = os.path.join(mapDir,"image")
                imageSrc =  mapData["src"]
                del mapData["src"]
                if not os.path.exists(imgDir):
                    os.makedirs(imgDir)
                print(f"---->切割图片")
                split_image(imageSrc, imgDir, (conf["image_size"], conf["image_size"]))
                print(f"---->生成小地图")
                create_small(imageSrc, mapDir, conf["smallScale"])
                save_json_file(os.path.join(mapDir,"data.json") ,mapData,None,separators=(",", ":"))
                print(f"{mapName}处理完成")

        input("打包成功按任意键退出")
               
    
